package com.flst.xlbibliotheque;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;

import com.flst.xlbibliotheque.api.Author;
import com.flst.xlbibliotheque.api.Book;
import com.flst.xlbibliotheque.api.dao.AuthorDao;
import com.flst.xlbibliotheque.api.dao.BookDao;
import com.flst.xlbibliotheque.entity.AuthorImpl;
import com.google.inject.Inject;
import com.google.inject.Singleton;

@SuppressWarnings("unchecked")
@Singleton
public class JPAAuthorDao implements AuthorDao{
       
        @Inject
        private EntityManager em;
       
        @Inject
        BookDao bDAO;
       
        @Override
        public void saveEntry(Author author) {
                EntityTransaction tx = em.getTransaction();
               
                tx.begin();
                em.persist(author);
                tx.commit();
        }


        @Override
        public Author getAuthor(Long id) {
                return em.find(AuthorImpl.class, id);
        }
       

        @Override
        public List<Author> getAuthors() {
                return em.createNamedQuery(AuthorImpl.ALL_AUTHOR).getResultList();
        }

        @Override
        public List<Author> getAuthorByNom(String nom) {
                Query query = em.createNamedQuery(AuthorImpl.AUTHOR_BY_NAME);
               
                return query.setParameter("nom", nom).getResultList();
        }

       

        @Override
        public AuthorImpl get(Long id) {
                return em.find(AuthorImpl.class, id);
        }


		@Override
		public List<Author> getAuthorsByBook(Book book) {
			List<Author> authors_from_book = new ArrayList<Author>();
			 List<Author> authors= em.createNamedQuery(AuthorImpl.ALL_AUTHOR).getResultList();
			 for(Author author:authors){
				 if(author.getBooks().contains(book)) authors_from_book.add(author);
			 }
             return authors_from_book;
		}




		@Override
		public Author createAuthor(String p) {
			return new AuthorImpl(p);
		}



}


